package com.gpframework.module.controller.ctn;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.exception.BaseException;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.ctn.domain.GpCtnOrder;
import com.gpframework.module.ctn.domain.GpItemTranslation;
import com.gpframework.module.ctn.domain.GpSackInformation;
import com.gpframework.module.ctn.domain.req.GpSackInformationReq;
import com.gpframework.module.ctn.domain.req.GpSackInformationUpdate;
import com.gpframework.module.ctn.domain.vo.CtnLoadListTemplate;
import com.gpframework.module.ctn.domain.vo.GpSackInformationExcel;
import com.gpframework.module.ctn.domain.vo.GpSackInformationVo;
import com.gpframework.module.ctn.service.IGpCtnOrderService;
import com.gpframework.module.ctn.service.IGpItemTranslationService;
import com.gpframework.module.ctn.service.IGpSackInformationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName GpSackInformationController
 * @Author gpframework
 * @Date 2024-02-28
 * @Version 1.0.0
 * @Description 散货信息填写Controller
 */
@Validated
@Api(tags = "散货信息填写")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/ctn/gpsackinformation" )
public class GpSackInformationController extends BaseController {

    private final IGpSackInformationService iGpSackInformationService;
    private final IGpCtnOrderService iGpCtnOrderService;
    private final IGpItemTranslationService iGpItemTranslationService;

 /**
  * @Description 分页
  * @Author gpframework
  * @Date 2024-02-28
  * @Param gpSackInformation
  * @Return TableDataInfo
 */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('ctn:gpsackinformation:list')")
    @GetMapping("/list")
    public TableDataInfo<GpSackInformationVo> list(GpSackInformationReq gpSackInformationReq)
    {
        startPage();
        QueryWrapper<GpSackInformation> lqw = new QueryWrapper<GpSackInformation>();
        gpSackInformationReq.generatorQuery(lqw,true);
        List<GpSackInformationVo> list = iGpSackInformationService.listVo(lqw);
        return getDataTable(list);
    }

    @ApiOperation("散货信息填写列表")
    @PreAuthorize("@ss.hasPermi('ctn:gpsackinformation:list')")
    @GetMapping("/listed")
    public TableDataInfo<GpSackInformationVo> listed(GpSackInformationReq gpSackInformationReq)
    {
        startPage();
        QueryWrapper<GpSackInformation> lqw = new QueryWrapper<GpSackInformation>();
        gpSackInformationReq.generatorQuery(lqw,true);
        List<GpSackInformationVo> list = iGpSackInformationService.listVoed(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-02-28
     * @Param gpSackInformation
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('ctn:gpsackinformation:add')" )
    @Log(title = "添加散货信息填写" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GpSackInformationUpdate gpPackagesInformationUpdate) {
       //return toAjax(iGpSackInformationService.addBatch(gpPackagesInformationUpdate));
        return AjaxResult.error();
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-02-28
     * @Param gpSackInformation
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('ctn:gpsackinformation:edit')" )
    @Log(title = "修改散货信息填写" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit( @RequestBody GpSackInformationUpdate gpSackInformationUpdate) {
        List<GpSackInformation> convert = Convert.convert(new TypeReference<List<GpSackInformation>>() {
        }, gpSackInformationUpdate.getGpSackInformationList());
        return toAjax(iGpSackInformationService.updateBatchById(convert) ? 1 : 0);
    }


    /**
     * @Description 导出散货信息填写模板
     * @Author gpframework
     * @Date 2023-05-24
     * @Param gpCustomer
     * @Return TableDataInfo
     */
    @ApiOperation("导出散货信息填写模板")
    @Log(title = "导出散货信息填写模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate" )
    public AjaxResult exportTemplate() {
        ExcelUtil<GpSackInformationExcel> util = new ExcelUtil<>(GpSackInformationExcel.class);
        return util.exportExcel(GpSackInformationExcel.list(), "模板");
    }

    /**
     * @Description 导入散货信息填写
     * @Author gpframework
     * @Date 2023-10-27
     * @Param (GpMember
     * @Return TableDataInfo
     */
    @Log(title = "导入散货信息填写" , businessType = BusinessType.IMPORT)
    @PostMapping("/import" )
    public AjaxResult entityImport(MultipartFile file, Long brandId, Long storeId) throws Exception {
        ExcelUtil<GpSackInformationExcel> util = new ExcelUtil<GpSackInformationExcel>(GpSackInformationExcel. class);
        List<GpSackInformationExcel> excelList = util.importExcel(file.getInputStream());

        return AjaxResult.builder(() -> {
            return this.iGpSackInformationService.gpSackInformationImport(excelList, brandId, storeId);
        });
    }

    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2024-02-28
     * @Param gpSackInformation
     * @Return TableDataInfo
     */

    @PreAuthorize("@ss.hasPermi('ctn:gpsackinformation:export')" )
    @Log(title = "导出散货信息填写" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(GpSackInformationReq gpSackInformationReq) {
        QueryWrapper<GpSackInformation> lqw = new QueryWrapper<GpSackInformation>();
        gpSackInformationReq.generatorQuery(lqw,true);
        List<GpSackInformationVo> list = iGpSackInformationService.listVo(lqw);
        ExcelUtil<GpSackInformationVo> util = new ExcelUtil<GpSackInformationVo>(GpSackInformationVo. class);
        return util.exportExcel(list, "gpsackinformation" );
    }

    @PreAuthorize("@ss.hasPermi('ctn:gpsackinformation:export')" )
    @Log(title = "导出装货柜散货分单" , businessType = BusinessType.EXPORT)
    @ApiOperation("导出装货柜散货分单")
    @PostMapping("/exportContainerSplitting" )
    public AjaxResult exportContainerSplitting(@RequestBody GpSackInformationReq gpSackInformationReq) throws IOException {
        GpSackInformation gpSackInformationOne = null;
        ArrayList<GpSackInformationExcel> informationExcels = new ArrayList<>();
        CtnLoadListTemplate ctnLoadListTemplate = new CtnLoadListTemplate();
        BigDecimal total = new BigDecimal("0");
        BigDecimal totalPack = new BigDecimal("0");
        for (GpSackInformationReq gpSackInformationReqs : gpSackInformationReq.getGpSackInformationReqList()) {
            gpSackInformationOne = iGpSackInformationService.getOne(new LambdaQueryWrapper<GpSackInformation>()
                    .eq(GpSackInformation::getCtnOrderId, gpSackInformationReqs.getCtnOrderId())
                    .eq(GpSackInformation::getId,gpSackInformationReqs.getId())
                    .eq(GpSackInformation::getDelStatus, YesNoEnum.NO.getKey())
                    .last("limit 1"));

            if (gpSackInformationOne!=null){
                GpSackInformationExcel gpSackInformationExcel = new GpSackInformationExcel();
                //gpSackInformationExcel.setCustomer(gpSackInformationOne.getCustomer()+ "-" + gpSackInformationOne.getPackNo());
                //gpSackInformationExcel.setGoodsDescription(gpSackInformationOne.getGoodsDescription() + "-" + gpSackInformationOne.getPackNo());
                //gpSackInformationExcel.setCbm(gpSackInformationOne.getCbm() + "-" + gpSackInformationOne.getPackNo());


                gpSackInformationExcel.setCustomer(gpSackInformationOne.getCustomer());

                GpItemTranslation gpItemTranslation = iGpItemTranslationService.getOne(new LambdaQueryWrapper<GpItemTranslation>().eq(GpItemTranslation::getChineseItem, gpSackInformationOne.getGoodsDescription()).eq(GpItemTranslation::getDelStatus, YesNoEnum.NO.getKey()));
                if (gpItemTranslation==null){
                    gpSackInformationExcel.setGoodsDescription(gpSackInformationOne.getGoodsDescription());
                }
                if (gpItemTranslation!=null && gpItemTranslation.getEnglishItem()!=null){
                    gpSackInformationExcel.setGoodsDescription(gpItemTranslation.getEnglishItem());

                }

                gpSackInformationExcel.setCbm(gpSackInformationOne.getCbm() );
                if (!gpSackInformationOne.getCustomerTel().isEmpty()){
                    // 获取第一个字符并检查是否为数字
                    char firstDigit  = gpSackInformationOne.getCustomerTel().charAt(0);
                    if (Character.isDigit(firstDigit)){
                        if (firstDigit == '1') {
                            //电话号码的第一个数字是1 +keep
                            gpSackInformationExcel.setCustomerTel("keep"+gpSackInformationOne.getCustomerTel()+ "-" + gpSackInformationOne.getCustomer());
                        } else {
                            gpSackInformationExcel.setCustomerTel(gpSackInformationOne.getCustomerTel()+ "-" + gpSackInformationOne.getCustomer());
                        }
                    } else {
                        throw new BaseException("电话号码的第一个字符不是数字");
                    }
                }
                //gpSackInformationExcel.setPackNo(gpSackInformationOne.getPackNo() + "-" + gpSackInformationOne.getPackNo());
                //gpSackInformationExcel.setPackagesNum(gpSackInformationOne.getPackagesNum() + "-" + gpSackInformationOne.getPackNo());
                //gpSackInformationExcel.setReceiptNo(gpSackInformationOne.getReceiptNo() + "-" + gpSackInformationOne.getPackNo());
                gpSackInformationExcel.setReceiptNo(gpSackInformationOne.getReceiptNo());


                if (gpSackInformationExcel.getCbm()!=null){
                    String[] cbm = gpSackInformationExcel.getCbm().split("-");
                    total = total.add(new BigDecimal(cbm[0]));
                }

                //if (gpSackInformationExcel.getPackNo()!=null){
                //    totalPack= totalPack.add(new BigDecimal("1"));
                //}
                informationExcels.add(gpSackInformationExcel);
            }

            ctnLoadListTemplate.setTotalCbm(total.stripTrailingZeros().toPlainString());
            ctnLoadListTemplate.setTotalPack(totalPack);

            if (StringUtil.isNotEmpty(gpSackInformationOne.getCustomer())){
                ctnLoadListTemplate.setCustomer(gpSackInformationOne.getCustomer());
            }
            if (StringUtil.isNotEmpty(gpSackInformationOne.getCustomerTel())){
                if (!gpSackInformationOne.getCustomerTel().isEmpty()){
                    // 获取第一个字符并检查是否为数字
                    char firstDigit  = gpSackInformationOne.getCustomerTel().charAt(0);
                    if (Character.isDigit(firstDigit)){
                        if (firstDigit == '1') {
                            //电话号码的第一个数字是1 +keep
                            ctnLoadListTemplate.setCustomerTel("keep"+gpSackInformationOne.getCustomerTel()+ "-" + gpSackInformationOne.getCustomer());
                        } else {
                            ctnLoadListTemplate.setCustomerTel(gpSackInformationOne.getCustomerTel()+ "-" + gpSackInformationOne.getCustomer());
                        }
                    } else {
                        throw new BaseException("电话号码的第一个字符不是数字");
                    }
                }
            }

        }

        //最外层 给个OrderId
        List<Long> ctnOrderIdList = gpSackInformationReq.getGpSackInformationReqList().stream()
                .map(GpSackInformationReq::getCtnOrderId)
                .collect(Collectors.toList());
        boolean allCtnOrderIdEqual = ctnOrderIdList.stream().distinct().limit(2).count() <= 1;
        if (allCtnOrderIdEqual){
            GpCtnOrder gpCtnOrder = iGpCtnOrderService.getOne(new LambdaQueryWrapper<GpCtnOrder>().eq(GpCtnOrder::getId, gpSackInformationReq.getCtnOrderId()).eq(GpCtnOrder::getDelStatus, YesNoEnum.NO.getKey()));

            if (gpCtnOrder.getCtnNo()!=null){
                ctnLoadListTemplate.setLoadCtnNo(gpCtnOrder.getAgentCtnNo());
            }
            if (gpCtnOrder.getLoadedDate()!=null){
                ctnLoadListTemplate.setLoadedDate(DateUtils.parseDateToStr("dd-MM-yyyy",gpCtnOrder.getLoadedDate()));
            }
        }else {
            throw new BaseException("请选择在同一个柜里面的相同的包信息");
        }

        List<String> allCtnCustomerList = gpSackInformationReq.getGpSackInformationReqList().stream().map(GpSackInformationReq::getCustomer).collect(Collectors.toList());
        boolean allCtnCustomerEqual=allCtnCustomerList.stream().distinct().limit(2).count()>1;
        if (allCtnCustomerEqual){
            throw new BaseException("请选择在同一个客户的包信息");
        }

        InputStream inputStream = new URL("https://haihe.gpinfo.com.cn/excelTemplate/SupplierCustomlistTemplate.xlsx").openStream();

        return AjaxResult.success(iGpSackInformationService.getString(informationExcels,ctnLoadListTemplate, inputStream,"散货装柜分单.xlsx").getUrl());
    }


    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-02-28
     * @Param gpSackInformation
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('ctn:gpsackinformation:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GpSackInformationVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGpSackInformationService.getVoById(id));
    }



    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-02-28
     * @Param gpSackInformation
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('ctn:gpsackinformation:remove')" )
    @Log(title = "删除散货信息填写" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGpSackInformationService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


    /**
     * @Description 复制
     * @Author gpframework
     * @Date 2023-12-11
     * @Param gpGramWeight
     * @Return TableDataInfo
     */
    @ApiOperation("复制")
    @PreAuthorize("@ss.hasPermi('module:gramweight:add')" )
    @Log(title = "复制" , businessType = BusinessType.INSERT)
    @PostMapping("/copy")
    public AjaxResult copy(@Valid @RequestBody GpSackInformationUpdate gpSackInformationUpdate) {
        if (gpSackInformationUpdate == null || gpSackInformationUpdate.getId() == null || gpSackInformationUpdate.getCopyNum() == null) {
            return AjaxResult.parameterError();
        }
        if (gpSackInformationUpdate.getCopyNum() < 1) {
            return AjaxResult.error("复制条数不能小于1");
        }
        return toAjax(iGpSackInformationService.copy(gpSackInformationUpdate.getId(), gpSackInformationUpdate.getCopyNum()) ? 1 : 0);
    }




}
